package com.zzp.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzp.pojo.TbBrand;
import com.zzp.pojo.TbCategory;
import com.zzp.pojo.TbGood;
import com.zzp.service.BrandService;
import com.zzp.service.CategoryService;
import com.zzp.service.GoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class IndexController {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private GoodService goodService;

    @RequestMapping("index")
    public String index(Model model,
                        String categoryId,
                        String brandId,
                        @RequestParam(defaultValue = "1") Integer pageNum,
                        @RequestParam(defaultValue = "2") Integer pageSize){
        List<TbCategory> categoryList = categoryService.selectAll();

        //一、查分类、如果没有传递分类id那么默认使用第一个分类的id
        if (categoryId == null){
            categoryId =String.valueOf(categoryList.get(0).getCategoryId());
        }
        //将分类id保存到域对象中
        model.addAttribute("categoryId",categoryId);
        model.addAttribute("categoryList",categoryList);


        //二、查品牌。根据分类id查询所有品牌
        List<TbBrand> brandList = brandService.selectBrandByCategoryId(categoryId);
        model.addAttribute("brandList",brandList);


    //三、根据品牌id和分类id查询商品
        //如果brandId第一次没有值的时候。默认使用第一个品牌下的第一个id
            if (brandList != null && brandList.size()>0){
                if (brandId == null){
                    brandId = String.valueOf(brandList.get(0).getBrandId());
                }
                //将品牌id保存到域对象中
                model.addAttribute("brandId",brandId);

                Page<TbGood> page = goodService.selectGoodByBrandIdAndCategoryId(brandId, categoryId,pageNum,pageSize);
                model.addAttribute("goodList",page.getRecords());//分页数据
                model.addAttribute("pages",page.getPages());//总页数
                model.addAttribute("total",page.getTotal()); //总条数
                model.addAttribute("current",page.getCurrent()); //当前页码
                model.addAttribute("size",page.getSize()); //每一页条数

            }
        return "index";

    }
}
